package com.abel.web.controller;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.abel.domain.AuthPrincipal;
import com.abel.domain.Education;
import com.abel.domain.MilitaryService;
import com.abel.domain.PersonProfile;
import com.abel.manager.PersonProfileManager;
import com.abel.manager.exception.EducationException;
import com.abel.manager.exception.WorkExperienceException;
import com.abel.repository.exception.RepositoryException;
import com.abel.util.UserSessionLocator;
import com.abel.web.view.MilitaryServiceViewBean;
import com.abel.web.view.WorkExperienceViewBean;

public class MilitaryServiceController extends SimpleFormController {

	protected final Log logger = LogFactory.getLog(getClass());

	private PersonProfileManager personProfileManager;
	
	private String previousView;
	
	
	/* (non-Javadoc)
	 * @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, org.springframework.validation.BindException)
	 */
	@Override
	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {

		MilitaryServiceViewBean bean = (MilitaryServiceViewBean)command;
		ModelAndView mav = null;

		Map<String, Object> modelMap = new HashMap<String, Object>();

		String action = request.getParameter("previous") != null ? "previous" : "continue";

		
		if (new Integer(bean.getDelId()).intValue() != 0 ) {
	        
			try {
				MilitaryService militaryService = UserSessionLocator.getUserSession().getPerson().getApplication().getPersonProfile().getMilitaryServiceInformation();
				personProfileManager.deleteMilitaryserviceInfo(militaryService);
			
			} 
			catch (Exception e) {
	    	
				e.printStackTrace();
	    		logger.error("@MilitaryServiceController : onSubmit : exception " + e);
	    		errors.rejectValue("", "error.null",null,"A system error occurred while deleting Military Service information. Please log out and log back in.");
	    		return showForm(request,response,errors);
			}
		}
		else {
			
			MilitaryService militaryService = new MilitaryService();
			this.convertViewToMilitaryService(militaryService, bean);
			
			try {
				
				personProfileManager.updateMilitaryserviceInfo(militaryService);
			
			}
			catch (Exception e) {
			
				e.printStackTrace();
				logger.error("@MilitaryServiceController : onSubmit : exception " + e);
				errors.rejectValue("", "error.null",null,"A system error occurred while registering Military Service information. Please log out and log back in.");
				return showForm(request,response,errors);
			}
		}
		
		if (action != null && action.equals("previous")) {
			mav = new ModelAndView("redirect:" + getPreviousView());
		}
		else {
			mav = new ModelAndView("redirect:" + getSuccessView());
		}
		mav.addAllObjects(modelMap);
		
		return mav;
	}


		/* (non-Javadoc)
		 * @see org.springframework.web.servlet.mvc.AbstractFormController#formBackingObject(javax.servlet.http.HttpServletRequest)
		 */
		@Override
		protected Object formBackingObject(HttpServletRequest request)
				throws Exception {
			
			//get Information from threadlocal
			PersonProfile personProfile = UserSessionLocator.getUserSession().getPerson().getApplication().getPersonProfile();

			String delIdStr = request.getParameter("delId");
			
			if (delIdStr != null) {
		        
				try {
				
		        	personProfileManager.deleteMilitaryserviceInfo(personProfile.getMilitaryServiceInformation());
		    	
		        }
		        catch (Exception e) {
		    			
		        	e.printStackTrace();
		    		logger.error("@MilitaryServiceController : onSubmit : exception " + e);
		    	}
			}
			
			MilitaryServiceViewBean viewBean = new MilitaryServiceViewBean();
			AuthPrincipal authPrincipal = UserSessionLocator.getUserSession().getAuthPrincipal();
	    	viewBean.setSalutation(authPrincipal.getUserName());
			if (personProfile.getMilitaryServiceInformation() == null) {
				//entering info for the first time
				return viewBean;
			}
			else {
				//information already exists - returning user
				MilitaryService militaryService = personProfile.getMilitaryServiceInformation();
				this.convertMilitaryServiceToView(militaryService, viewBean);
				return viewBean;
			}
		}

		/**
		 * @param personProfileManager the personProfileManager to set
		 */
		public void setPersonProfileManager(PersonProfileManager personProfileManager) {
			this.personProfileManager = personProfileManager;
		}

		
    private void convertViewToMilitaryService(MilitaryService militaryService, MilitaryServiceViewBean viewBean) {
    	
    	militaryService.setMltServiceId(viewBean.getMltServiceId());
    	
    	if (viewBean.getAplId()==0 ) { 
    		
    		militaryService.setAplId(UserSessionLocator.getUserSession().getPerson().getApplication().getApplicationId());
    	}
    	else {
    		
    		militaryService.setAplId(viewBean.getAplId());
    	}
		
    	if (viewBean.getInductionDate() != null && viewBean.getInductionDate() != "") {
			
    		try{
				
    			SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy"); 
				militaryService.setMltInductionDate(dateFormat.parse(viewBean.getInductionDate())); 
			}
			catch (Exception e) {
				
				System.out.println("Error converting string to InductionDate");
				e.printStackTrace();
			}
		}
		if (viewBean.getDischargeDate() != null && viewBean.getDischargeDate() != "") {
			
			try{
				
				SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy"); 
				militaryService.setMltDischargeDate(dateFormat.parse(viewBean.getDischargeDate())); 
			}
			catch (Exception e) {
				
				System.out.println("Error converting string to DischargeDate");
				e.printStackTrace();
			}
		}
    	
		militaryService.setMltBranch(viewBean.getBranch());
    	militaryService.setMltRank(viewBean.getRank());
    	militaryService.setMltDutyDesc(viewBean.getDuties());
    	militaryService.setMltSplTrainDesc(viewBean.getSpecialTraining());
    }

    private void convertMilitaryServiceToView(MilitaryService militaryService, MilitaryServiceViewBean viewBean) {
    	
    	DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
    	viewBean.setAplId(militaryService.getAplId());
    	viewBean.setMltServiceId(militaryService.getMltServiceId());
    	
    	if (militaryService.getMltInductionDate() !=null) {
    		viewBean.setInductionDate(df.format(militaryService.getMltInductionDate()));
    	}
    	if (militaryService.getMltDischargeDate() != null) {
    		viewBean.setDischargeDate(df.format(militaryService.getMltDischargeDate()));
    	}
    	viewBean.setBranch(militaryService.getMltBranch());
    	viewBean.setRank(militaryService.getMltRank());
    	viewBean.setDuties(militaryService.getMltDutyDesc());
    	viewBean.setSpecialTraining(militaryService.getMltSplTrainDesc());
    }


	/**
	 * @return the previousView
	 */
	public String getPreviousView() {
		return previousView;
	}


	/**
	 * @param previousView the previousView to set
	 */
	public void setPreviousView(String previousView) {
		this.previousView = previousView;
	}
    
    

}
